package com.solocredit.finance.data.dev

import android.content.Context
import com.google.gson.Gson
import com.solocredit.finance.data.dev.take.TakeFlexiMolaBte
import com.solocredit.finance.data.dev.take.TakeFlexiMolaDev
import com.solocredit.finance.data.dev.take.TakeFlexiMolaHdw
import com.solocredit.finance.data.dev.take.TakeFlexiMolaNet
import com.solocredit.finance.data.dev.take.TakeFlexiMolaSd
import com.solocredit.finance.data.dev.take.TakeFlexiMolaMsage
import com.solocredit.finance.data.dev.take.TakeFlexiMolaApp

class FlexiMolaDevMode(val context: Context, val product: String, val token: String) {

    private fun mode1(path: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted

        // TODO: 不加密
        return content
    }

    private fun mode2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val data = fetchData() ?: return null
        val params = baseJson(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted

        // TODO: 不加密
        return content
    }

    private fun formatJson(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun baseJson(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun iWishDe(path: String) = mode1(path) {
        TakeFlexiMolaDev(context, product, token, path).takeFlexiMolaDev()
    }

    fun iWishSm(path: String) = mode1(path) {
        TakeFlexiMolaMsage(context, product, token, path).takeFlexiMolaMsage()
    }

    fun iWishHd(path: String) = mode2(path, "deviceHardwareGzip") {
        TakeFlexiMolaHdw(context).takeFlexiMolaHdw()
    }

    fun iWishBty(path: String, onResult: (String?) -> Unit) {
        TakeFlexiMolaBte(context = context, onResult = { bd ->
            val result = mode2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun iWishNw(path: String) = mode2(path, "deviceWifiGzip") {
        TakeFlexiMolaNet(context).takeFlexiMolaNet()
    }

    fun iWishRm(path: String) = mode2(path, "deviceStorageGzip") {
        TakeFlexiMolaSd(context).takeFlexiMolaSd()
    }

    fun iWishAp(path: String) = mode2(path, "appListGzip") {
        TakeFlexiMolaApp(context).takeFlexiMolaApp()
    }
}